﻿using DAL;
using DAL.DBManagers;
using DAL.Models;
using System;
using System.Web.UI.WebControls;

public partial class PermissionManage : System.Web.UI.Page
{
    Guid UserID = Guid.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Guid.TryParse(Request.QueryString["id"], out UserID))
        {
            Response.Redirect("userview.aspx");
        }

        PermissionsManager mng = new PermissionsManager();
        var prms = mng.GetUserPermission(UserID);
        foreach (var item in prms)
        {
            var input = new CheckBox()
            {
                ID = item.PermissionID.ToString(),
                Checked = item.IsChecked,
                Text = item.PermissionName,
                AutoPostBack = true,
                CssClass = "left"
            };
            input.CheckedChanged += input_CheckedChanged;
            pnlPermissions.Controls.Add(input);
        }
    }

    protected void input_CheckedChanged(object sender, EventArgs e)
    {
        var checkbox = (CheckBox)sender;

        using (UserPermissionsManager manager = new UserPermissionsManager())
        {
            var permissioninuser = manager.SingleOrDefault(s => s.PermissionID == Guid.Parse(checkbox.ID) && s.UserID == UserID);

            if (permissioninuser == null)
            {
                manager.Add(new UserPermission
                    {
                        UserPermissionID = Guid.NewGuid(),
                        UserID = UserID,
                        PermissionID = Guid.Parse(checkbox.ID),
                        IsActive = true,
                        CreateDate = DateTime.Now,
                        CreatedBy = (Session["User"] as UserHelper).UserID
                    });
            }
            else
            {
                permissioninuser.LastModifyDate = DateTime.Now;
                permissioninuser.LastModifier = (Session["User"] as UserHelper).UserID;
                permissioninuser.IsActive = checkbox.Checked;
            }

            manager.SaveChanges();
        }
    }
}